package com.yxh.bigdata.zookeeper.zk;


import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.util.ArrayList;
import java.util.List;

public class DistributedClient {

    private static final String CONNECT_HOST = "localhost:2181";
    private static final int SESSION_TIMEOUT = 2000;
    private static ZooKeeper zkClient = null;
    private static volatile List<String> serverList = null;

    public static void main(String[] args) throws Exception {
        //获取链接
        zkClient = getConnect();
        //获取监听
        zkClient.getChildren("/servers", true);
        //业务代码
        Thread.sleep(Long.MAX_VALUE);
    }

    private static ZooKeeper getConnect() throws Exception {
        return new ZooKeeper(CONNECT_HOST, SESSION_TIMEOUT, event -> {
            //收到事件通知后的通知函数
            try {
                List<String> servers = new ArrayList<>();
                List<String> children = zkClient.getChildren("/servers", true);
                for (String child : children){
                    servers.add(new String(zkClient.getData("/servers/"+child, false, null)));
                }
                serverList = servers;
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
